/**
 * 任务块编辑功能模块
 * 包含双击编辑任务块的所有相关功能
 */

export class TaskBlockEditor {
  constructor(vueInstance) {
    this.vm = vueInstance
  }

  /**
   * 处理任务块双击事件
   * @param {Event} event - 鼠标事件
   * @param {Object} item - 任务块项目
   */
  handleItemDoubleClick(event, item) {
    event.stopPropagation()
    
    // 双击：进入编辑界面
    this.vm.selectedScheduleItem = item
    this.editScheduleItem()
  }

  /**
   * 编辑任务块
   */
  editScheduleItem() {
    // 检查是否有多选任务块
    const hasMultipleSelection = this.vm.selectedItems.length > 1
    const itemsToEdit = hasMultipleSelection ? this.vm.selectedItems : (this.vm.selectedScheduleItem ? [this.vm.selectedScheduleItem] : [])
    
    if (itemsToEdit.length === 0) {
      return
    }
    
    if (hasMultipleSelection) {
      // 多选编辑模式：使用第一个任务块的数据作为模板
      const firstItem = itemsToEdit[0]
      
      // 检查所有选中任务块的名称是否相同
      const allTitles = itemsToEdit.map(item => item.title)
      const hasCommonTitle = allTitles.every(title => title === allTitles[0])
      
      // 如果多选的任务块名称不相同，禁止编辑并显示提示
      if (!hasCommonTitle) {
        alert('无法编辑：选中的任务块名称不相同，请选择相同名称的任务块进行批量编辑。')
        return
      }
      
      this.vm.editingItem = {
        id: 'multiple', // 特殊标识表示多选编辑
        title: allTitles[0], // 所有任务块名称相同时显示
        satelliteId: null, // 多选时可能跨卫星
        duration: firstItem.duration || 1,
        requiredDevices: firstItem.requiredDevices ? [...firstItem.requiredDevices] : (firstItem.requiredDevice ? [firstItem.requiredDevice] : []),
        deviceCapacities: firstItem.deviceCapacities ? {...firstItem.deviceCapacities} : {},
        dayConfigs: firstItem.dayConfigs ? [...firstItem.dayConfigs] : [],
        selectedItemsCount: itemsToEdit.length, // 记录选中的任务块数量
        selectedItemIds: itemsToEdit.map(item => item.id) // 记录选中的任务块ID
      }
    } else {
      // 单选编辑模式：使用原有逻辑
      const item = itemsToEdit[0]
      
      this.vm.editingItem = {
        id: item.id,
        title: item.title,
        satelliteId: item.satelliteId,
        duration: item.duration || 1,
        requiredDevices: item.requiredDevices ? JSON.parse(JSON.stringify(item.requiredDevices)) : (item.requiredDevice ? [item.requiredDevice] : []),
        deviceCapacities: item.deviceCapacities ? JSON.parse(JSON.stringify(item.deviceCapacities)) : {},
        dayConfigs: item.dayConfigs ? JSON.parse(JSON.stringify(item.dayConfigs)) : [],
        selectedItemsCount: 1,
        selectedItemIds: [item.id]
      }
    }
    
    // 初始化设备容量（如果没有保存的容量配置，使用默认值）
    this.initializeDeviceCapacities()
    
    // 确保dayConfigs数组长度与duration匹配，每个元素都是数组
    while (this.vm.editingItem.dayConfigs.length < this.vm.editingItem.duration) {
      this.vm.editingItem.dayConfigs.push([])
    }
    // 确保现有的每个元素都是数组
    this.vm.editingItem.dayConfigs = this.vm.editingItem.dayConfigs.map(dayConfig => 
      Array.isArray(dayConfig) ? dayConfig : (dayConfig ? [dayConfig] : [])
    )
    
    this.vm.editItemVisible = true
    if (this.vm.hideContextMenu) {
      this.vm.hideContextMenu()
    }
  }

  /**
   * 关闭编辑弹窗
   */
  closeEditItem() {
    this.vm.editItemVisible = false
    this.vm.showDeviceDropdown = false
    this.vm.editingItem = {
      id: null,
      title: '',
      satelliteId: null,
      duration: 1,
      requiredDevices: [],
      deviceCapacities: {},
      dayConfigs: []
    }
  }

  /**
   * 保存编辑的任务块
   */
  async saveEditItem() {
    if (!this.vm.editingItem.title.trim()) {
      alert('请输入任务名称')
      return
    }
    
    // 在编辑保存前保存历史记录
    if (this.vm.saveToHistory) {
      this.vm.saveToHistory()
    }
    
    if (this.vm.editingItem.id === 'multiple') {
      // 批量编辑模式：更新所有选中的任务块
      const updatedCount = this.vm.editingItem.selectedItemIds.length
      let successCount = 0
      
      this.vm.editingItem.selectedItemIds.forEach(itemId => {
        const itemIndex = this.vm.scheduleItems.findIndex(item => item.id === itemId)
        if (itemIndex !== -1) {
          const originalItem = this.vm.scheduleItems[itemIndex]
          const originalDuration = originalItem.duration
          const newDuration = this.vm.editingItem.duration
          
          // 重新计算actualStartDate
          const newActualStartDate = new Date(this.vm.startDate)
          newActualStartDate.setDate(newActualStartDate.getDate() + originalItem.startDay)
          
          // 更新任务块数据
          this.vm.scheduleItems[itemIndex] = {
            ...this.vm.scheduleItems[itemIndex],
            title: this.vm.editingItem.title.trim(),
            duration: this.vm.editingItem.duration,
            requiredDevices: [...this.vm.editingItem.requiredDevices],
            deviceCapacities: {...this.vm.editingItem.deviceCapacities},
            dayConfigs: [...this.vm.editingItem.dayConfigs],
            actualStartDate: newActualStartDate.toISOString().split('T')[0]
          }
          
          // 如果持续时间发生变化，需要重新排列后续任务块以避免重叠
          if (originalDuration !== newDuration) {
            const updatedItem = this.vm.scheduleItems[itemIndex]
            const originalEndPosition = originalItem.startDay + originalDuration
            const newEndPosition = updatedItem.startDay + updatedItem.duration
            
            // 如果新的结束位置超过了原始结束位置，需要重新排列后续任务块
            if (newEndPosition > originalEndPosition && this.vm.autoArrangeSubsequentTasks) {
              this.vm.autoArrangeSubsequentTasks(
                updatedItem.satelliteId,
                originalEndPosition,
                newEndPosition - originalEndPosition,
                [updatedItem.id]
              )
            }
          }
          
          successCount++
        }
      })
      
      console.log(`批量编辑完成：成功更新 ${successCount}/${updatedCount} 个任务块`)
      
      // 清空选中状态
      if (this.vm.clearSelection) {
        this.vm.clearSelection()
      }
      
    } else {
      // 单个编辑模式
      const itemIndex = this.vm.scheduleItems.findIndex(item => item.id === this.vm.editingItem.id)
      
      if (itemIndex !== -1) {
        const originalItem = this.vm.scheduleItems[itemIndex]
        const originalDuration = originalItem.duration
        const originalStartDay = originalItem.startDay
        const newDuration = this.vm.editingItem.duration
        
        const originalEndPosition = originalStartDay + originalDuration
        
        // 重新计算actualStartDate
        const newActualStartDate = new Date(this.vm.startDate)
        newActualStartDate.setDate(newActualStartDate.getDate() + originalItem.startDay)
        
        // 更新任务块数据
        this.vm.scheduleItems[itemIndex] = {
          ...this.vm.scheduleItems[itemIndex],
          title: this.vm.editingItem.title.trim(),
          duration: this.vm.editingItem.duration,
          requiredDevices: [...this.vm.editingItem.requiredDevices],
          deviceCapacities: {...this.vm.editingItem.deviceCapacities},
          dayConfigs: [...this.vm.editingItem.dayConfigs],
          actualStartDate: newActualStartDate.toISOString().split('T')[0]
        }
        
        // 如果持续时间发生变化，需要重新排列后续任务块以避免重叠
        if (originalDuration !== newDuration) {
          const updatedItem = this.vm.scheduleItems[itemIndex]
          const newEndPosition = updatedItem.startDay + updatedItem.duration
          
          // 如果新的结束位置超过了原始结束位置，需要重新排列后续任务块
          if (newEndPosition > originalEndPosition && this.vm.autoArrangeSubsequentTasks) {
            this.vm.autoArrangeSubsequentTasks(
              updatedItem.satelliteId,
              originalEndPosition,
              newEndPosition - originalEndPosition,
              [updatedItem.id]
            )
          }
        }
      }
    }
    
    // 进行全局设备冲突检测
    if (this.vm.detectDeviceConflicts) {
      const conflicts = this.vm.detectDeviceConflicts()
      if (conflicts.length > 0 && this.vm.markConflictingTasks) {
        this.vm.markConflictingTasks(conflicts)
      } else if (this.vm.clearConflictMarks) {
        this.vm.clearConflictMarks()
      }
    }
    
    // 确保显示天数足够包含修改后的任务块
    if (this.vm.ensureSufficientDays) {
      this.vm.ensureSufficientDays()
    }
    
    this.closeEditItem()
  }

  /**
   * 初始化设备容量
   */
  initializeDeviceCapacities() {
    this.vm.editingItem.requiredDevices.forEach(deviceName => {
      if (!this.vm.editingItem.deviceCapacities[deviceName]) {
        // 先尝试从同一卫星的相同任务块名称中获取设备容量
        let sameTaskCapacity = null
        if (this.vm.getDeviceCapacityFromSameTaskName) {
          sameTaskCapacity = this.vm.getDeviceCapacityFromSameTaskName(
            this.vm.editingItem.satelliteId, 
            this.vm.editingItem.title, 
            deviceName
          )
        }
        
        if (sameTaskCapacity !== null) {
          this.vm.editingItem.deviceCapacities[deviceName] = sameTaskCapacity
        } else {
          // 如果没有相同任务块，使用默认容量
          if (this.vm.getDefaultDeviceCapacity) {
            this.vm.editingItem.deviceCapacities[deviceName] = this.vm.getDefaultDeviceCapacity(deviceName)
          } else {
            this.vm.editingItem.deviceCapacities[deviceName] = 1 // 默认容量
          }
        }
      }
    })
  }

  /**
   * 更新设备容量
   * @param {string} deviceName - 设备名称
   * @param {number} value - 容量值
   */
  async updateDeviceCapacity(deviceName, value) {
    const numericCapacity = parseInt(value) || 0
    this.vm.editingItem.deviceCapacities[deviceName] = numericCapacity
    
    // 同步到同一卫星中相同任务块名称的其他任务块
    if (this.vm.synchronizeDeviceCapacityBySameTaskName) {
      this.vm.synchronizeDeviceCapacityBySameTaskName(
        this.vm.editingItem.satelliteId, 
        this.vm.editingItem.title, 
        deviceName, 
        numericCapacity
      )
    }
    
    // 更新实际的scheduleItems中的数据
    const itemIndex = this.vm.scheduleItems.findIndex(item => item.id === this.vm.editingItem.id)
    if (itemIndex !== -1) {
      this.vm.scheduleItems[itemIndex].deviceCapacities = {...this.vm.editingItem.deviceCapacities}
    }
  }
}